<?php

namespace app\xs_test\controller\pc;

use xsframe\base\ApiBaseController;
use xsframe\exception\ApiException;
use xsframe\facade\service\PayServiceFacade;
use xsframe\util\ErrorUtil;
use xsframe\util\PriceUtil;

class Pay extends ApiBaseController
{

    /**
     * 支付宝支付
     * @return array
     */
    public function alipay(): array
    {
        $ordersn = $this->params['ordersn'];
        $price = 100.00;                                // 支付金额
        $service = 1;                                   // 支付服务类型（1.商品支付，2课程支付，3余额支付，4积分支付等等）
        $title = "购买商品";                            // 支付标题
        $returnUrl = $this->params['returnUrl'] ?? '';
        $returnQrcode = false; // 是否返回支付二维码
        $qrcodeWidth = 300;    // $returnQrcode = true 时有效 二维码的宽度

        $codeUrl = PayServiceFacade::aliPagePay($ordersn, $price, $service, $title, $returnUrl, $returnQrcode, $qrcodeWidth);

        $result = [
            'codeUrl' => $codeUrl,
        ];
        return $this->success($result);
    }

    /**
     * wap - 微信js sdk支付
     *
     * @param $ordersn
     * @return array
     */
    public function wechatPay($ordersn): array
    {
        $openid = "oDQpnwZpjj2Ysu5YRH9ZsR5rniFs";       // openid
        $ordersn = "2023110234545646544";               // 商户订单号
        $price = 100.00;                                // 支付金额
        $service = 1;                                   // 支付服务类型（1.商品支付，2课程支付，3余额支付，4积分支付等等）
        $title = "购买商品";                            // 支付标题

        $unifiedReturn = PayServiceFacade::wxPay($ordersn, $price, $title, $service, $openid);

        $result = [
            'appId'     => $unifiedReturn['appId'],
            'timeStamp' => $unifiedReturn['timeStamp'],
            'nonceStr'  => $unifiedReturn['nonceStr'],
            'package'   => $unifiedReturn['package'],
            'signType'  => $unifiedReturn['signType'],
        ];
        return $this->success($result);
    }


    /**
     * 微信Native支付
     *
     * @return array
     * @throws ApiException
     */
    public function wxNative()
    {
        $ordersn = "2023110234545646544";               // 商户订单号
        $price = 100.00;                                // 支付金额
        $service = 1;                                   // 支付服务类型（1.商品支付，2课程支付，3余额支付，4积分支付等等）
        $title = "购买商品";                            // 支付标题

        $unifiedReturn = PayServiceFacade::wxNative($ordersn, $price, $service, $title);

        if (ErrorUtil::isError($unifiedReturn)) {
            throw new ApiException($unifiedReturn['msg']);
        } else {
            $codeUrl = $unifiedReturn['code_url'];
        }

        $result = [
            'ordersn' => $ordersn,
            'price'   => PriceUtil::numberFormat($this->params['price']),
            'codeUrl' => $codeUrl,
        ];
        return $this->success($result);
    }

}